package com.glsc.ngateway.opmanage.service.report.excel.listener.regulatory;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.read.metadata.holder.ReadRowHolder;
import com.glsc.ngateway.common.base.domain.mysql.opmanage.report.fileupload.ImportTemplateRulesDefine;
import com.glsc.ngateway.common.base.domain.mysql.opmanage.report.regulatory.RegRptSAJSIMS;
import com.glsc.ngateway.common.base.repo.mysql.opmanage.report.regulatory.RegRptSAJSIMSRepo;
import com.glsc.ngateway.opmanage.service.report.excel.listener.TemplateCheckHandler;
import org.springframework.util.CollectionUtils;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author: qiyr
 * @date: 2022/8/31 10:38
 * @description: 江苏省证券业协会信息管理系统实体数据导入监听器
 */
public class RegRptSAJSIMSListener extends AnalysisEventListener<RegRptSAJSIMS> {

    private static final int BATCH_COUNT = 3000;
    List<RegRptSAJSIMS> list = new ArrayList<>();

    private List<ImportTemplateRulesDefine> rulesDefineList;
    private RegRptSAJSIMSRepo regRptSAJSIMSRepo;
    private BigInteger mainId;

    public RegRptSAJSIMSListener() {
    }

    public RegRptSAJSIMSListener(RegRptSAJSIMSRepo regRptSAJSIMSRepo, BigInteger mainId,
                                 List<ImportTemplateRulesDefine> rulesDefineList) {
        this.regRptSAJSIMSRepo = regRptSAJSIMSRepo;
        this.mainId = mainId;
        this.rulesDefineList = rulesDefineList;
    }

    @Override
    public void invoke(RegRptSAJSIMS data, AnalysisContext context) {
        TemplateCheckHandler.check(context, rulesDefineList);
        ReadRowHolder readRowHolder = context.readRowHolder();
        Integer rowIndex = readRowHolder.getRowIndex();
        data.setMainId(mainId);
        data.setRowId(rowIndex + 1);
        list.add(data);

        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (list.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            list.clear();
        }
    }

    //读取表头内容
    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        TemplateCheckHandler.check(context, rulesDefineList);
    }


    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData();
    }

    private void saveData() {
        if (CollectionUtils.isEmpty(list)) {
            throw new RuntimeException("导入失败，数据量为空，请检查文件格式与内容");
        }
        regRptSAJSIMSRepo.saveAll(list);
    }
}
